package org.yi.fc.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.yi.fc.enums.ArticleStatusEnum;

import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * 枚举工具类
 * @author ilgqh
 *
 */
public class EnumsUtil {
	
	/**
	 * 根据名称获取值
	 * @param name   		要获取的值的名称
	 * @param enumObj		枚举实例
	 * @param clazz			枚举类的类型
	 * @return
	 * @throws NoSuchMethodException 
	 * @throws SecurityException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws InstantiationException
	 * @throws IllegalAccessException
	 */
	public static  Object getValue(String name, Object enumObj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
		Preconditions.checkNotNull(Strings.emptyToNull(name), "传入的名称不允许为空!");
		Preconditions.checkNotNull((enumObj != null && enumObj.getClass().isEnum()), "enumObj不允许为空且必须为枚举类型!");
		
		Object [] objs = enumObj.getClass().getEnumConstants();
		String methodName = getGetMethod(name);
		
		for(Object obj : objs){
			if(Objects.equal(obj, enumObj)){
				Method method = enumObj.getClass().getMethod(methodName, null);
				method.setAccessible(true);
				return method.invoke(enumObj, null);
			}
		}
		
		return null;
	}
	
	/**
	 * 根据名称获取对应的get方法名
	 * @param name
	 * @return
	 */
	private static String getGetMethod(String name){
		Preconditions.checkNotNull(Strings.emptyToNull(name), "传入的名称不允许为空!");
		String firstChar = String.valueOf(name.charAt(0));
		return "get" + name.replaceFirst(firstChar, firstChar.toUpperCase());
	}
	
	public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
		Object obj = getValue("cnName", ArticleStatusEnum.FORBID);
		System.out.println(obj.toString());
	}
}
